<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="text"> 
    <button class="send">点击发送</button>
    <button class="close">点击关闭</button>
    <div class="container"></div>
</body>
</html>
<script>
    let con = document.querySelector('.container')
    let socket = new WebSocket('wss://echo.websocket.org')
    socket.onopen = function(){
        con.innerHTML += '<p style="color:red">服务器连接成功</p>'
        
    }
    let btn1 = document.querySelector('input')
    document.querySelector('.send').onclick = function(){
        con.innerHTML += `<p style="color:red">用户:${btn1.value}</p>`
        socket.send(btn1.value)
    }
    socket.onmessage = function(data){
        con.innerHTML += `<p style="color:red">服务器:${data.data}</p>`
    }
    document.querySelector('.close').onclick = function(){
        socket.close()
    }
    socket.onclose = function(){
        con.innerHTML += '<p style="color:red">服务器已关闭</p>'
    }
</script>